﻿//Description:订单导入
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2020-4-16
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using System.Data;
using uMES.LeanManufacturing.ParameterDTO;
using System.Drawing;
using System.IO;
using Infragistics.WebUI.UltraWebNavigator;
using Infragistics.WebUI.UltraWebGrid;

public partial class Custom_BwPlanManager_BwMfgorderViewForm2 : BaseForm
{
    // Dictionary<string, string> userInfo;
    int m_PageSize = 20;
    BwMfgorderImportBusiness mfgOrderImportBal = new BwMfgorderImportBusiness();
    uMESProductTreeViewBusiness productTreeBal = new uMESProductTreeViewBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：批次创建";
        master.strTitle = "批次创建";
        master.ChangeFrame(true);

        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(()=> { ProductTreeSearch(); });

        ClearMessage();
        if (!IsPostBack)
        {
            getProductInfo.GetProductControlDiv.Style["width"] = "190px";
            getProductInfo.GetSearchBtn.Visible=false;
        }
    }
    

    #region 事件
    protected void btnTreeSearch_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try {
            TreeSearchProduct();
           // ProductTreeSearch();

        } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try { SearchData(1); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearMessage();

        //$("#dvPopupClosedButton").find(':submit').click();


        ResetData();

    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);


        DataTable dt = uMESCommonFunction.GetGridChooseInfo(gdMfgorder, null, "ckSelect");

        if (dt.Rows.Count != 1)
        {
            ShowStatusMessage("请选择单条记录", false);
            return;
        }

        PopupData = dt;

        var page = "BwContainerStartPopupForm.aspx";
        var strScript = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 1260, 450);
        
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

        // ShowPopupPage("123.aspx", 1000, 500, true);


        //var pop = PopupData;
        //if (pop == null)
        //    DisplayMessage(lStatusMessage, "qwerty", false);
        //else
        //{ DisplayMessage(lStatusMessage, pop as string, false);
        //    SearchData(1);
        //}

    }
    protected void btnStarts_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("",true);
        DataTable dt = uMESCommonFunction.GetGridChooseInfo(gdMfgorder, null, "ckSelect");

        if (dt.Rows.Count < 2)
        {
            //DisplayMessage(lStatusMessage, "请选择多条记录", false);
            //return;
        }

        PopupData = dt;

        var page = "BwContainerBatchStartPopupForm.aspx";
        var strScript = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 1280, 550);

        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }
    
    protected void popupClosedButton_Click(object sender, EventArgs e)
    {

        if (PopupData == null)
        {
            return;
        }

        Dictionary<string, string> result = PopupData as Dictionary<string, string>;

        if (result["Page"] == "BwContainerBatchStartPopupForm.aspx")
        {
            SearchData(1);
            //ShowStatusMessage(result["Message"], true);
        }

    }

    protected void tvTree_SelectedNodeChanged(object sender, EventArgs e)
    {
        try { ResetData(); selectProductNode(); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }
  
    protected void treeProduct_NodeSelectionChanged(object sender, WebTreeNodeEventArgs e)
    {
        try
        {
            upageTurning.InitControl();
            ResetData();
           selectProductNode();
           // ShowStatusMessage(DateTime.Now.Second.ToString(), true);

        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }
    protected void btnSearchAll_Click(object sender, EventArgs e)
    {
        try { upageTurning.Disabled(); SearchAllData2(); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    //产品结构树区域 重置
    protected void btnTreeReset_Click(object sender, EventArgs e)
    {
        try {
            ResetData();
            txtTreeProcessNo.Text = string.Empty;
            getProductInfo.InitControl();
            tvTree.Nodes.Clear();
            treeProduct.Nodes.Clear();
        } catch (Exception ex) {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnSelectAll_Click(object sender, EventArgs e)
    {
        if (btnSelectAll.Text == "全选")
        {
            btnSelectAll.Text = "全不选";
            uMESCommonFunction.ResetGridCheckStatus2(gdMfgorder, "ckSelect", 0);
        }
        else if (btnSelectAll.Text == "全不选")
        {
            btnSelectAll.Text = "全选";
            uMESCommonFunction.ResetGridCheckStatus2(gdMfgorder, "ckSelect", 2);
        }

    }

    protected void btnInRevert_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus2(gdMfgorder, "ckSelect", 1);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = gdMfgorder.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("WorkflowID").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);

            //string strScript = string.Empty;
            //strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

            var page = "../bwCommonPage/uMESDocumentViewPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    #region 方法
    /// <summary>
    /// 选择节点
    /// </summary>
    void selectProductNode() {
        // var selectNode = tvTree.SelectedNode;
        // string productID = selectNode.Value;
        upageTurning.Disabled();
       var selectNode = treeProduct.SelectedNode;
        string productID = selectNode.Tag.ToString();

        txtSrTreeProduct.Text = selectNode.Text;
        txtSrTreeProcessNo.Text = txtTreeProcessNo.Text;
        SearchData2(GetSerachCondition2(1, selectNode.Text));
    }

    /// <summary>
    /// 查询订单
    /// </summary>
    /// <param name="index"></param>
    void SearchData(int index)
    {
        gdMfgorder.Rows.Clear();
        upageTurning.Enabled();
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["MfgManagerID"] = UserInfo["EmployeeID"];
        para["ProcessNo"] = txtProcessNo.Text.Trim();
        para["OprNo"] = txtOprNo.Text.Trim();
        para["ProductName"] = txtProductName.Text.Trim();
        para["PlannedStartDate1"] = txtPlanStartDate1.Value.Trim();
        para["PlannedStartDate2"] = txtPlanStartDate2.Value.Trim();

        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();


        uMESPagingDataDTO result = mfgOrderImportBal.GetSearchData(para);

        this.gdMfgorder.DataSource = result.DBTable;
        this.gdMfgorder.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        
        //ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), strScript);
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }

    /// <summary>
    /// 清除提示信息
    /// </summary>
    protected override void ClearMessage()
    {
        ShowStatusMessage("",true);
    }

    void ResetData()
    {
        // Response.Redirect(Request.Url.AbsoluteUri);
        txtProcessNo.Text = string.Empty;
        txtOprNo.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtPlanStartDate1.Value = string.Empty;
        txtPlanStartDate2.Value = string.Empty;
        txtSrTreeProcessNo.Text = string.Empty;
        txtSrTreeProduct.Text = string.Empty;
        gdMfgorder.Clear();
        ShowStatusMessage("", true);
    }

    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        if (productInfo == "")
        {
            return;
        }

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    TreeNode GetProductTree(string productName, string productRev, DataTable dt)
    {
        TreeNode productTree = new TreeNode();

        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));


        for (int i = 0; i < drs.Length; i++)
        {
            TreeNode productSubTree = GetProductTree(drs[i]["subproductname"].ToString(), drs[i]["subproductrev"].ToString(), dt);

            productSubTree.Text = drs[i]["subproductname"].ToString() + ":" + drs[i]["subproductrev"].ToString(); //+ " | " + drs[i]["subproductstatus"].ToString();
            productSubTree.Value = drs[i]["subproductid"].ToString();
            productTree.ChildNodes.Add(productSubTree);
        }

        return productTree;

    }

    

    /// <summary>
    /// 产品结构树
    /// </summary>
    void ProductTreeSearch() {
        tvTree.Nodes.Clear();treeProduct.Nodes.Clear();

        string productName = "", productRev = "";
        GetProductInfo(ref productName, ref productRev);
        if (string.IsNullOrWhiteSpace(productName))
        {
            ShowStatusMessage("请选择产品", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", productName); para.Add("ProductRev", productRev);
        para.Add("ProcessNo", txtTreeProcessNo.Text);//工作令号
        DataTable dt = productTreeBal.GetSubProductInfo(para);

        if (dt.Rows.Count == 0)
        {
            ShowStatusMessage("此产品没有子级零组件", false);
            return;
        }
        //TreeView
        /*
        TreeNode productTree = GetProductTree(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString() + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Value = drs[0]["productid"].ToString();
        tvTree.Nodes.Add(productTree);
        tvTree.Nodes[0].Expand();
        */
        //UltraWebTree
        Node productTree = GetProductTree2(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString(); //+ ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Tag = drs[0]["productid"].ToString();
        treeProduct.Nodes.Add(productTree);
        treeProduct.Nodes[0].Expand(false);
    }

    /// <summary>
    /// 获取查询数据
    /// </summary>
    /// <returns></returns>
    Dictionary<string, string> GetSerachCondition(int index,string productID) {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();
        para["MfgManagerID"] = UserInfo["EmployeeID"];
        para["ProductID"] = productID;
        para["ProcessNo"] = txtTreeProcessNo.Text;
        return para;
    }

    Dictionary<string, string> GetSerachCondition2(int index, string productName)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();
        para["MfgManagerID"] = UserInfo["EmployeeID"];
        para["ProductName2"] = productName;
        para["ProcessNo"] = txtTreeProcessNo.Text;
        return para;
    }

    /// <summary>
    /// 查询2
    /// </summary>
    /// <param name="index"></param>
    /// <param name="para"></param>
    void SearchData2( Dictionary<string, string> para) {
        gdMfgorder.Rows.Clear();

        DataTable dt = mfgOrderImportBal.GetSearchData2(para);
        this.gdMfgorder.DataSource = dt;
        this.gdMfgorder.DataBind();

    }

    /// <summary>
    /// 查询该产品及其以下所有
    /// </summary>
    void SearchAllData() {
        gdMfgorder.Rows.Clear();

        var selectNode = tvTree.SelectedNode;
        if (selectNode == null) {
            ShowStatusMessage("请先选择节点",false);            
            return;
        }

        DataTable allDt = mfgOrderImportBal.GetSearchData2(GetSerachCondition2(1, selectNode.Value));
        GetChildNodesData(selectNode.ChildNodes,allDt);
        
        this.gdMfgorder.DataSource = allDt;
        this.gdMfgorder.DataBind();

    }

    /// <summary>
    /// 遍历所有子节点，并查询订单
    /// </summary>
    /// <param name="childNodes"></param>
    /// <param name="dt"></param>
    void GetChildNodesData(TreeNodeCollection childNodes,DataTable dt) {

        foreach (TreeNode node in childNodes) {
            DataTable tempDt = mfgOrderImportBal.GetSearchData2(GetSerachCondition2(1, node.Value));
            dt.Merge(tempDt);
            GetChildNodesData(node.ChildNodes,dt);
        }
    }

    #region 使用UltraWebTree控件
    //UltraWebTree
    Node GetProductTree2(string productName, string productRev, DataTable dt)
    {
        Node productTree = new Node();

        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));


        for (int i = 0; i < drs.Length; i++)
        {
            Node productSubTree = GetProductTree2(drs[i]["subproductname"].ToString(), drs[i]["subproductrev"].ToString(), dt);

            productSubTree.Text = drs[i]["subproductname"].ToString();//+ ":" + drs[i]["subproductrev"].ToString(); //+ " | " + drs[i]["subproductstatus"].ToString();
            productSubTree.Tag = drs[i]["subproductid"].ToString();
            if (drs[i]["IsCommon"].ToString() == "1")
            {
                productSubTree.Styles.ForeColor = Color.Blue ;
                productSubTree.ToolTip = "公共件";
            }
            productTree.Nodes.Add(productSubTree);
        }

        return productTree;

    }
    /// <summary>
    /// 查询该产品及其以下所有
    /// </summary>
    void SearchAllData2()
    {
        gdMfgorder.Rows.Clear();

        var selectNode = treeProduct.SelectedNode;
        if (selectNode == null)
        {
            ShowStatusMessage("请先选择节点", false);
            return;
        }
       // selectNode.nod
        DataTable allDt = mfgOrderImportBal.GetSearchData2(GetSerachCondition2(1, selectNode.Text.ToString()));
        GetChildNodesData2(selectNode.Nodes, allDt);

        this.gdMfgorder.DataSource = allDt;
        this.gdMfgorder.DataBind();

    }

    /// <summary>
    /// 遍历所有子节点，并查询订单
    /// </summary>
    /// <param name="childNodes"></param>
    /// <param name="dt"></param>
    void GetChildNodesData2(Nodes childNodes, DataTable dt)
    {

        foreach (Node node in childNodes)
        {
            DataTable tempDt = mfgOrderImportBal.GetSearchData2(GetSerachCondition2(1, node.Text.ToString()));
            dt.Merge(tempDt);
            GetChildNodesData2(node.Nodes, dt);
        }
    }
    #endregion

    /// <summary>
    /// 根据工作令号查询产品
    /// </summary>
    void TreeSearchProduct() {
        treeProduct.Nodes.Clear();
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        DataTable dt = containerBal.GetProductByProcess(txtTreeProcessNo.Text);
        getProductInfo.GetProductDDL.Visible = true;
        getProductInfo.GetProductNameOrTypeText.Visible = false;

        getProductInfo.GetProductDDL.DataTextField = "PRODUCTNAME";
        getProductInfo.GetProductDDL.DataValueField = "PRODUCTID";
        getProductInfo.GetProductDDL.DataSource = dt;
        getProductInfo.GetProductDDL.DataBind();

        getProductInfo.GetProductDDL.Items.Insert(0, "");
    }

    #endregion







}